<template>
    <div class="wrap" v-if="mobileApp">
        <div v-if="config.advConfig"><filter-params :config="config" :filterParams="[]" ></filter-params></div>
        <div v-if="config.advConfig.legendShow" :class="{'left-top':(config.advConfig.legendLeft=='left' && config.advConfig.legendTop=='top'),'center-top':(config.advConfig.legendLeft=='center' && config.advConfig.legendTop=='top'),'right-top':(config.advConfig.legendLeft=='right' && config.advConfig.legendTop=='top'),'bottom-left':(config.advConfig.legendLeft=='left' && config.advConfig.legendTop=='bottom'),'bottom-center':(config.advConfig.legendLeft=='center' && config.advConfig.legendTop=='bottom'),'bottom-right':(config.advConfig.legendLeft=='right' && config.advConfig.legendTop=='bottom')}">
            <span v-for="legend in legends">
                <a-tag @click="legendClick(legend)" :color="legend.color || 'blue'">{{legend.label}}</a-tag>
            </span>
        </div>
        <div style="height: 100%" :ref="config.alias"></div>
    </div>
</template>

<script>
// #ifdef H5
import * as echarts from 'echarts';
import ChartPublic from '../ChartPublic.js';
// #endif
export default {
    /**
     * 地图
     */
    name: "mapComponent",
    // #ifdef H5
    mixins: [ChartPublic],
    // #endif
    data() {
        return {
            //图例 {label:"",color:""}
            legends:[],
            colorSettings:[],
            visualMapConf:{
                left: 'right',
                min: 0,
                max: 5000,
                inRange: {
                    color: ['lightskyblue', 'yellow', 'orangered']
                },
                text: ['High', 'Low'],           // 文本，默认为数值文本
                calculable: true,
            },
            mobileApp:false
        }
    },
    created(){
        // #ifdef H5
        this.mobileApp = true
        // #endif
    },
    methods: {
        loadView  (map)  {
            var path = import.meta.env.JPAAS_BASE_URL;
            var promise = new Promise(function(resolve){
                let url=`${path}/province/${map}.json`;
                fetch(url).then(response => {
                    resolve(response.json());
                })
            })
            return promise;
        },
        async setOption() {
            let mapType = this.config.mapType_ || this.config.mapType || "china";
            let json = await this.loadView(mapType);
            let data = this.getData();
            let visualMap = undefined;
            if (this.config.visualMap) {
                if (this.colorSettings && this.colorSettings.length > 0) {
                    let colorSetting = this.colorSettings[0];
                    this.visualMapConf.min = colorSetting.min ? colorSetting.min : this.visualMapConf.min;
                    this.visualMapConf.max = colorSetting.max ? colorSetting.max : this.visualMapConf.max;
                    this.visualMapConf.left = colorSetting.alignment ? colorSetting.alignment : this.visualMapConf.left;
                    this.visualMapConf.inRange.color = colorSetting.colors ? colorSetting.colors : this.visualMapConf.inRange.color;
                }
                visualMap = this.visualMapConf;
            }
            this.option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        let res = params.name + '<br/>';
                        for (let i = 0; i < data.length; i++) {
                            if (data[i].name == params.name) {
                                let values = data[i].values || [];
                                for (let j = 0; j < values.length; j++) {
                                    res += values[j].name + ' : ' + values[j].value + '</br>';
                                }
                            }
                        }
                        return res;
                    }
                },
                toolbox: {
                    feature: {
                        saveAsImage: {show: this.config.advConfig.saveAsImage},
                        restore: {show: this.config.advConfig.restore}
                    }
                },
                visualMap: visualMap,
                series: [
                    {
                        name: this.config.name,
                        type: 'map',
                        mapType: mapType, // 自定义扩展图表类型
                        label: {
                            show: true
                        },
                        roam: true, //是否开启平游或缩放
                        scaleLimit: { //滚轮缩放的极限控制
                            min: 1,
                            max: 10
                        },
                        data: data
                    },
                ]
            }
        },
        getData(){
            /**
             *  {
                name: '广东省',
                itemStyle: {
                    normal: {
                        areaColor: '#FBE0EC'
                    }
                },
                values:[
                    {"name": "广州市", "value": 200},
                    {"name": "深圳市", "value": 500},
                    {"name": "东莞市", "value": 100}
                ]
            }
             */
            let data=[];
            //地图颜色配置
            let colorSetting={};
            if(!this.config.dimensions || this.config.dimensions.length==0){
                return data;
            }
            //未配置颜色图例
            if(!this.config.isLegend || this.config.colorLegends.length==0){
                let legends=[];
                for (let i = 0; i < this.data.length; i++) {
                    let obj={};
                    //地址字段
                    let dimension=this.config.dimensions[0];
                    let dimensionVal= this.data[i][dimension.tableName+'_'+dimension.fieldName];
                    //配置了字段渲染
                    if(dimensionVal && typeof(dimensionVal) !="string"){
                        obj.name=dimensionVal.newValue;
                        dimensionVal=dimensionVal.oldValue;
                    }else {
                        obj.name=dimensionVal;
                    }
                    let values=[];
                    //获取度量
                    for (let j = 0; j < this.config.measures.length; j++) {
                        let measure=this.config.measures[j];
                        if(measure.colorSetting){
                            //启用视觉映射
                            if(this.config.visualMap){
                                this.colorSettings.push({
                                    label:measure.fieldLabel,
                                    colors:measure.colorSetting.colors,
                                });
                            }else if(measure.colorSetting.settings){
                                //地图颜色配置 默认取最前的
                                if(!colorSetting.colors || colorSetting.colors.length==0){
                                    colorSetting={
                                        colors:measure.colorSetting.settings,
                                        label:measure.fieldLabel
                                    };
                                }
                                this.colorSettings.push(colorSetting);
                            }
                        }
                        let measureVal= this.data[i][measure.tableName+'_'+measure.fieldName];
                        let legend= legends.find(item=>(item.label==measure.fieldLabel));
                        if(!legend){
                            legends.push({
                                label:measure.fieldLabel
                            });
                        }
                        values.push({
                            name:measure.fieldLabel,
                            value:measureVal
                        });
                    }
                    obj.values=values;
                    if(values.length>0){
                        obj.value=values[0].value
                    }else {
                        obj.value=0
                    }
                    data.push(obj);
                }
                this.legends=legends;
            }else {
                //图例组件配置
                let legends = [];
                //地址字段
                let dimension=this.config.dimensions[0];
                //根据颜色图例与度量获取图例组件
                for (let i = 0; i < this.config.colorLegends.length; i++) {
                    let colorLegend = this.config.colorLegends[i];
                    if(colorLegend.colorSetting){
                        //启用视觉映射
                        if(this.config.visualMap){
                            this.colorSettings.push(...colorLegend.colorSetting);
                            //地图颜色配置 默认取最前的
                            colorSetting={
                                colors:colorLegend.colorSetting[0].colors,
                                label:colorLegend.colorSetting[0].label,
                                newLabel:colorLegend.colorSetting[0].newLabel,
                            };
                        }else if(colorLegend.colorSetting[0].settings){
                            if(!colorSetting.colors || colorSetting.colors.length==0){
                                //地图颜色配置 默认取最前的
                                colorSetting={
                                    colors:colorLegend.colorSetting[0].settings,
                                    label:colorLegend.colorSetting[0].label,
                                    newLabel:colorLegend.colorSetting[0].newLabel,
                                };
                            }
                            this.colorSettings.push(...colorLegend.colorSetting);
                        }
                    }
                    for (let j = 0; j < this.data.length; j++) {
                        let obj={};
                        let dimensionVal= this.data[j][dimension.tableName+'_'+dimension.fieldName];
                        //配置了字段渲染
                        if(typeof(dimensionVal) !="string" ){
                            obj.name=dimensionVal.newValue;
                            dimensionVal=dimensionVal.oldValue;
                        }else {
                            obj.name=dimensionVal;
                        }
                        let values=[];
                        let value=this.data[j][colorLegend.tableName+'_'+colorLegend.fieldName];
                        if(colorSetting.colors && colorSetting.colors.length>0){
                            let legend= "";
                            if(colorSetting.newLabel && value==colorSetting.label){
                                legend= legends.find(item=>(item.label==colorSetting.newLabel));
                                value=colorSetting.newLabel;
                            }else {
                                legend= legends.find(item=>(item.label==value));
                            }
                            if(!legend){
                                legends.push({
                                    label:value
                                });
                            }
                        }
                        //获取度量
                        for (let k = 0; k < this.config.measures.length; k++) {
                            let measure=this.config.measures[k];
                            let measureVal= this.data[j][measure.tableName+'_'+measure.fieldName];
                            values.push({
                                name:value,
                                value:measureVal
                            });
                        }
                        obj.values=values;
                        if(values.length>0){
                            obj.value=values[0].value
                        }else {
                            obj.value=0
                        }
                        data.push(obj);
                    }
                }
                let newData=[];
                for (let i = 0; i < data.length; i++) {
                    let name=data[i].name;
                    let obj=newData.find(item => item.name==name);
                    if(!obj){
                        newData.push(data[i]);
                    }else {
                        if(!obj.values){
                            obj.values=[];
                        }
                        obj.values.push(...data[i].values);
                    }
                }
                data=newData;
                this.legends=legends;
            }
            if(!this.config.visualMap && colorSetting.colors && colorSetting.colors.length){
                data=this.calColor(data,colorSetting);
            }
            return data;
        },
        /**
         * 计算颜色
         * @param data 数据
         * @param colorSetting 颜色配置
         */
        calColor(data,colorSetting){
            for (let i = 0; i < data.length; i++) {
                let values=data[i].values;
                if(values){
                    for (let j = 0; j < values.length; j++) {
                        if(values[j].name==colorSetting.label || (colorSetting.newLabel && values[j].name==colorSetting.newLabel)){
                            let areaColor=this.getColor(values[j].value,colorSetting.colors);
                            if(areaColor){
                                let  itemStyle= {normal: {areaColor: areaColor}};
                                data[i]["itemStyle"]=itemStyle;
                            }
                        }
                    }
                }
            }
            return data;
        },
        /**
         * 根据值获取颜色
         * @param value
         * @param colors
         */
        getColor(value,colors){
            let color="";
            if((!value && value!=0) || !colors){
                return color;
            }
            for (let i = 0; i < colors.length; i++) {
                switch(colors[i].express_value){
                    case 'eq':
                        if(value==colors[i].express_name){
                            color=colors[i].color;
                        }
                        break;
                    case 'lt':
                        if(value<colors[i].express_name){
                            color=colors[i].color;
                        }
                        break;
                    case 'le':
                        if(value<=colors[i].express_name){
                            color=colors[i].color;
                        }
                    case 'gt':
                        if(value>colors[i].express_name){
                            color=colors[i].color;
                        }
                        break;
                    case 'ge':
                        if(value>=colors[i].express_name){
                            color=colors[i].color;
                        }
                    case 'in':
                        if(colors[i].express_name<=value && value<=colors[i].express_name2){
                            color=colors[i].color;
                        }
                    default:
                }
                //有颜色后结束循环
                if(color){
                    break;
                }
            }
            return color;
        },
        //图例点击事件
        legendClick(legend){
            //启用视觉映射组件
            if(this.config.visualMap){
                if(this.colorSettings && this.colorSettings.length>0){
                    for (let i = 0; i < this.colorSettings.length; i++) {
                        let colorSetting=this.colorSettings[i];
                        if((colorSetting.newLabel && colorSetting.newLabel==legend.label) || colorSetting.label==legend.label){
                            this.visualMapConf.min=colorSetting.min?colorSetting.min:this.visualMapConf.min;
                            this.visualMapConf.max=colorSetting.max?colorSetting.max:this.visualMapConf.max;
                            this.visualMapConf.left=colorSetting.alignment?colorSetting.alignment:this.visualMapConf.left;
                            this.visualMapConf.inRange.color=colorSetting.colors?colorSetting.colors:this.visualMapConf.inRange.color;
                            break;
                        }
                    }
                }
                this.option["visualMap"]=this.visualMapConf;
            }else {
                let colorSetting="";
                for (let i = 0; i < this.colorSettings.length; i++) {
                    if((this.colorSettings[i].newLabel && this.colorSettings[i].newLabel==legend.label) || this.colorSettings[i].label==legend.label){
                        colorSetting={
                            colors:this.colorSettings[i].settings,
                            label:this.colorSettings[i].label,
                            newLabel:this.colorSettings[i].newLabel,
                        }
                        break;
                    }
                }
                if(!colorSetting){
                    return;
                }
                let data=this.option.series[0].data;
                for (let i = 0; i < data.length; i++) {
                    let values=data[i].values;
                    if(values){
                        for (let j = 0; j < values.length; j++) {
                            if(values[j].name==colorSetting.label || (colorSetting.newLabel && values[j].name==colorSetting.newLabel)){
                                let areaColor=this.getColor(values[j].value,colorSetting.colors);
                                if(areaColor){
                                    let  itemStyle= {normal: {areaColor: areaColor}};
                                    data[i]["itemStyle"]=itemStyle;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</script>

<style scoped>
.wrap{
    position: relative;
}
.left-top{
    margin-left: 10px;

}
.center-top{
    text-align: center;
}
.right-top{
    text-align: right;
}
.bottom-left{
    position: absolute;
    bottom: 10px;
    left: 10px;
    z-index: 99;
}
.bottom-center{
    position: absolute;
    text-align: center;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%);
    z-index: 99;
}
.bottom-right{
    position: absolute;
    text-align: center;
    bottom: 10px;
    right: 10px;
    z-index: 99;
}
</style>
